import React, { Component } from 'react'

import { Link } from 'react-router-dom'
import { Toast } from 'antd-mobile'

import NavHeader from '../../components/NavHeader'
import HouseItem from '../../components/HouseItem'
import NoHouse from '../../components/NoHouse'

import styles from './index.module.css'

export default class Rent extends Component {
  state = {
    // 出租房屋列表
    list: [],
    // 是否加载中
    isLoading:false,
  }

  // 获取已发布房源的列表数据
  async getHouseList() {
    try {
      this.setState({
        isLoading:true,
      })
      // 开启loading
      Toast.loading('加载中...', 0, null, false);
      const res = await this.$axios("get", '/user/houses')
      Toast.hide();
      const { status, body } = res;
      if (status === 200) {
        this.setState({
          list: body,
          isLoading:false,
        })
      } else {
        const { history, location } = this.props;
        history.replace('/login', {
          from: location
        });
      }
    } catch (error) {
      Toast.hide();
    }
  }

  componentDidMount() {
    this.getHouseList();
  }

  renderHouseItem() {
    const { list } = this.state
    const { history } = this.props

    return list.map(item => {
      return (
        <HouseItem
          key={item.houseCode}
          onClick={() => history.push(`/detail/${item.houseCode}`)}
          src={this.baseUrl + item.houseImg}
          title={item.title}
          desc={item.desc}
          tags={item.tags}
          price={item.price}
        />
      )
    })
  }

  renderRentList() {
    const { list,isLoading } = this.state;
    const hasHouses = list.length > 0;

    if (!hasHouses) {
      return (
        isLoading?"":<NoHouse>
          您还没有房源，
          <Link to="/rent/add" className={styles.link}>
            去发布房源
          </Link>
          吧~
        </NoHouse>
      )
    }

    return <div className={styles.houses}>
      <Link to="/rent/add" className={styles.link1}>
        发布新房源
      </Link>
      {this.renderHouseItem()}
    </div>
  }

  render() {
    const { history } = this.props

    return (
      <div className={styles.root}>
        <NavHeader onLeftClick={() => history.go(-1)}>房屋管理</NavHeader>

        {this.renderRentList()}
      </div>
    )
  }
}
